"use strict";
/**
 * @name basics
 * 经典活动
 */

/**
 * @name submit
 * @param string id 活动ID
 * @param int ik 奖励编号
 * @param int num 兑换次数
 * 兑换奖励
 */
exports.submit = function () {
    let id = this.get('id'), ik = this.get('ik', 'int'), num = this.get('num', 'int');

    if (!id || !ik) {
        return this.error('args empty');
    }
    let api = '/active/', data = { "id": id, "ik": ik, "num": num };
    return this.library('spirit/gzone', api, data).then(ret => {
        if (!ret || !ret["item"] || !ret["item"][ik]) {
            return this.error("active_ik_empty", id, ik, num);
        }
        this.updater.active.key(id);  //shop/filter 中会执行一次this.updater.data()
        return this.library.call(this.updater, 'shop/filter', ret);
    }).then(config => {
        //console.log(config);
        let val = this.updater.active.get(id, ik) || 0;
        if (config["item"][ik]['max'] > 0 && val >= config["item"][ik]['max']) {
            return this.error('active_max_limit', val, config["item"][ik]['max']);
        }
        if (config["item"][ik]['dt'] > 0) {
            return verify_active_value.call(this, ik, config);
        }
        else {
            return config;
        }
    }).then(config => {
        //扣道具
        if (config["item"][ik]['sub']) {
            // console.log("扣件物品:",config["item"][ik]['sub'],num);
            for (let i = 0; i < num; i++) {
                this.library.call(this, 'shop/parse', config["item"][ik]['sub'], 1);
            }
        }
        //加道具
        if (config["item"][ik]['add']) {
            for (let i = 0; i < num; i++) {
                this.library.call(this, 'shop/parse', config["item"][ik]['add']);
            }
        }
        //写记录
        this.updater.active.add(id, ik, num, config['ETime']);
        return this.updater.save();
    })
}

function verify_active_value(ik, config) {
    let item = config["item"][ik];
    if (!item['dk']) {
        return this.error("active_dk_empty")
    }
    let tar = parseInt(item['dt']), key = item['dk'];
    if (tar == 800) {
        //特殊逻辑
        if (key == "FinishNum") {
            //BOBTODO 
            //做数量检查
            return config;
        }
    }

    return this.library.call(this.updater, "valuesNew", tar, key, config['STime'], config['ETime']).then(val => {
        if (val <= 0) {
            return this.error('active_val_limit1', item['dc'], 0, tar, key, config);
        }
        if (item['dc'] === 0 && val < item['val']) {
            return this.error('active_val_limit2', item['dc'], val, item['val']);
        }
        if (item['dc'] > 0 && val > item['val']) {
            return this.error('active_val_limit3', item['dc'], val, item['val']);
        }
        return config;
    })
}

